package demo.config;


import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
@MapperScan(basePackages = {"lc.secret.dao.master*"}, sqlSessionTemplateRef = "masterSqlSessionTemplate")
public class MasterSourceConfig {
     @Primary
    @Bean(name = "masterDataSource")
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource dataSourceOne() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "masterSqlSessionFactory")
    @Primary // 主数据源
    public SqlSessionFactory sqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        //sessionFactoryBean.setPlugins(new PaginationInterceptor[]{paginationInterceptor});
        List<Resource> resourceList = new ArrayList<>();
        //mapper
        String oaBaseResourceLocationPattern = "classpath*:lc/secret/mapper/master/**/*.xml";
        Resource[] approvalBaseResource = new PathMatchingResourcePatternResolver()
                .getResources(oaBaseResourceLocationPattern);
//        String oaResourceLocationPattern = "classpath*:lc/oa/mapper/*.xml";
//        Resource[] approvalResource = new PathMatchingResourcePatternResolver()
//                .getResources(oaResourceLocationPattern);
        resourceList.addAll(Arrays.asList(approvalBaseResource));
       // resourceList.addAll(Arrays.asList(approvalResource));

        sessionFactoryBean.setMapperLocations(resourceList.toArray(new Resource[resourceList.size()]));
        return sessionFactoryBean.getObject();
    }

    @Bean(name = "masterSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate masterSqlSessionTemplate(
            @Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
